import multiprocessing
import time
from django.shortcuts import render

from AppManager import Mysql
from OpManager import settings
from aliyunsdkcore.client import AcsClient
from aliyunsdkdomain.request.v20180129.QueryDomainListRequest import QueryDomainListRequest
from aliyunsdkalidns.request.v20150109.DescribeDomainRecordsRequest import DescribeDomainRecordsRequest
import json
from Logs import views as Logs_views


DomainDicts = multiprocessing.Manager().list(range(1))
DomainDicts[0] = {"Data": [{"Remark": "获取失败，请检查"}]}
HostDicts = multiprocessing.Manager().list(range(1))
HostDicts[0] = {"DomainList": []}


def startfork_domain():
    i = 0
    while True:
        forkget_domain()
        i += 1
        print("第" + str(i) + "次获取域名列表")
        time.sleep(60 * 15)


def forkget_domain():
    global DomainDicts
    global HostDicts
    sql = "SELECT * FROM `setting` WHERE id=1"
    setting_res = Mysql.MysqlPool(sql, 1)
    print("读取域名配置，方案id：", setting_res["id"])
    accessKeyId = setting_res["AliaccessKeyId"]
    accessSecret = setting_res["AliaccessSecret"]
    client = AcsClient(accessKeyId, accessSecret, 'cn-hangzhou')
    DomainDicts[0] = GetDomain_Ali(client)
    DomainList = []
    for domain in DomainDicts[0]["Data"]["Domain"]:
        # print(domain["DomainName"], end='')
        DomainList.append(domain["DomainName"])
        HostDicts[0] = {"DomainList": DomainList}
    HostDicts[0] = GetHost_Ali(client)
    # print(DomainDicts[0])
    # print(HostDicts[0])
    Logs_views.log("域名列表：" + str(HostDicts[0]))


def GetDomain_Ali(client):
    try:
        request = QueryDomainListRequest()
        request.set_accept_format('json')
        request.set_PageNum(1)
        request.set_PageSize(100)
        request.set_Lang("zh")

        response = client.do_action_with_exception(request)
        return json.loads(response)
    except Exception as e:
        print(e)
        return {"Data": ""}


def GetHost_Ali(client):
    request = DescribeDomainRecordsRequest()
    request.set_accept_format('json')
    DomainData = []
    for domain in HostDicts[0]["DomainList"]:
        try:
            request.set_DomainName(domain)
            request.set_Lang("zh")
            request.set_PageNumber(1)
            request.set_PageSize(100)

            response = client.do_action_with_exception(request)
            Datas = json.loads(response)["DomainRecords"]["Record"]
            for data in Datas:
                DomainData.append(data)
        except Exception as e:
            print(e)
            data = {
                "RR": "获取异常",
                "DomainName": domain
            }
            DomainData.append(data)
    Dicts = {
        "DomainList": HostDicts[0]["DomainList"],
        "Data": DomainData
        }
    return Dicts


# 域名列表界面
@settings.auth(AuthType="DomainManager", AuthNum=1)
def DomainManager(requests):
    if requests.method == 'GET':
        DomainDict = DomainDicts[0]["Data"]
        if DomainDict:
            context = {
                "domains": DomainDict["Domain"]
            }
        else:
            context = {
                "domainerror": "获取失败，请检查",
                "domains": [{"Remark": "获取失败，请检查"}]
            }
        # print(context)
        return render(requests, "DomainManager.html", context)


# 主机记录界面
@settings.auth(AuthType="DomainManager", AuthNum=2)
def DomainHost(requests):
    if requests.method == 'GET':
        HostDict = HostDicts[0]["Data"]
        context = {
                "hosts": HostDict
            }
        return render(requests, "DomainHost.html", context)


p = multiprocessing.Process(target=startfork_domain, args=())
p.start()
settings.PIDs.append(p.pid)
Logs_views.log("创建用于获取域名的子进程：" + str(p.pid))
